export const toSearchByJson = (data: any): string => {
    if (!isJson(data)) return '';
    let value: string = '';
    for (const item in data) {
        if (!data.hasOwnProperty(item)) continue;
        value += `${item}=${data[item]}&`;
    }
    if (value) value = value.substring(0, value.length - 1);
    return value;
}

export const toJsonBySearch = <T,>(search: string): T => {
    const result = {} as Record<string, string>;
    if (!search.length) return result as T;
    const strA = search.indexOf('?') >= 0 ? search.split('?')[1] : search;
    const strB = strA.split('&');
    for (let i = 0, len = strB.length; i < len; i++) {
        const item = strB[i].split('=');
        result[item[0]] = typeof item[1] === 'undefined' ? '' : item[1];
    }
    return result as T;
}

const isJson = (data: any): boolean => {
    try {
        if (typeof data === 'string') {
            return !!JSON.parse(data);
        } else if (typeof data === 'object') {
            if (typeof data.length === "number") return false;
        }
        const jsonToString = JSON.stringify(data);
        const stringToJson = JSON.parse(jsonToString);
        return !!stringToJson;
    } catch (err) {
        return false
    }
}
